/* simple_pipe.c

   Simple demonstration of the use of a pipe to communicate
   between a parent and a child process.

   Usage: simple_pipe "string"

   The program creates a pipe, and then calls fork() to create a child process.
   After the fork(), the parent writes the string given on the command line
   to the pipe, and the child uses a loop to read data from the pipe and
   print it on standard output.

   lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

#define BUF_SIZE 10

static void errExit(char *msg) {
  perror(msg);
  exit(EXIT_FAILURE);
}

int main(int argc, char *argv[]) {
  int pfd[2]; /* Pipe file descriptors */
  char buf[BUF_SIZE];
  ssize_t numRead;

  if (argc != 2 || strcmp(argv[1], "--help") == 0) {
    fprintf(stderr, "%s string\n", argv[0]);
    exit(EXIT_FAILURE);
  }

  /* Create the pipe */
  if (pipe(pfd) == -1) {
    errExit("pipe");
  }

  switch (fork()) {
    case -1:
      errExit("fork");

    case 0:                      /* Child  - reads from pipe */
      if (close(pfd[1]) == -1) { /* Write end is unused */
        errExit("close - child");
      }

      int cnt = 0;
      for (;;) { /* Read data from pipe, echo on stdout */
        numRead = read(pfd[0], buf, BUF_SIZE);
        if (numRead == -1) {
          errExit("read");
        }
        if (numRead == 0) break; /* End-of-file */
        if (write(STDOUT_FILENO, buf, numRead) != numRead) {
          errExit("child - partial/failed write");
        }
      }

      write(STDOUT_FILENO, "\n", 1);
      if (close(pfd[0]) == -1) {
        errExit("close");
      }
      _exit(EXIT_SUCCESS);

    default:                     /* Parent - writes to pipe */
      if (close(pfd[0]) == -1) { /* Read end is unused */
        errExit("close - parent");
      }

      if (write(pfd[1], argv[1], strlen(argv[1])) != strlen(argv[1])) {
        errExit("parent - partial/failed write");
      }

      if (close(pfd[1]) == -1) { /* Child will see EOF */
        errExit("close");
      }
      wait(NULL); /* Wait for child to finish */
      exit(EXIT_SUCCESS);
  }
}